package com.yunchao.library.socket.model.security

import com.yunchao.library.socket.constants.Limits
import com.yunchao.library.socket.extensions.toReadOnlyBuffer
import com.yunchao.library.socket.extensions.getByteArray
import com.yunchao.library.socket.extensions.hexString

data class DataExchange(
    val cHandler: UShort,
    val cApdu: ByteArray,
    val rHandler: UShort
) {
    init {
        require(cApdu.size <= Limits.MAX_APDU_SIZE) {
            "C-APDU length ${cApdu.size} exceeds maximum ${Limits.MAX_APDU_SIZE}"
        }
    }

    override fun toString(): String {
        return "DataExchange(cHandler=$cHandler, cApdu=${cApdu.hexString}, rHandler=$rHandler)"
    }

    companion object {
        //编号为 0x8001 的 handler 应该处理以下应答 APDU 数据
        const val HANDLER_ID: UShort = 0x8001u

        fun fromByteArray(bytes: ByteArray): DataExchange {
            val buffer = bytes.toReadOnlyBuffer()
            return DataExchange(
                cHandler = buffer.short.toUShort(),
                cApdu = buffer.getByteArray(buffer.int),
                rHandler = buffer.short.toUShort()
            )
        }
    }

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false
        other as DataExchange
        return cHandler == other.cHandler &&
                rHandler == other.rHandler &&
                cApdu.contentEquals(other.cApdu)
    }

    override fun hashCode(): Int {
        var result = cHandler.hashCode()
        result = 31 * result + cApdu.contentHashCode()
        result = 31 * result + rHandler.hashCode()
        return result
    }
}